package com.edu.study.base.stuProductCatalog.controller;

import com.edu.study.base.StuCommonClassifyCatalog.domain.StuCommonClassifyCatalog;
import com.edu.study.base.StuCommonClassifyCatalog.mapper.StuCommonClassifyCatalogMapper;
import com.edu.study.base.stuProductCatalog.domain.StuProductCatalog;
import com.edu.study.base.stuProductCatalog.service.IStuProductCatalogService;
import com.edu.study.base.stuProductCatalogTemplateData.domain.StuProductCatalogTemplateData;
import com.edu.study.base.stuProductCatalogTemplateData.service.IStuProductCatalogTemplateDataService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 产品（含章节层级）Controller
 *
 * @author zw
 * @date 2021-05-13
 */
@RestController
@RequestMapping("/product/productCatalog")
public class StuProductCatalogController extends BaseController {
    @Autowired
    private IStuProductCatalogService stuProductCatalogService;
    @Autowired
    private IStuProductCatalogTemplateDataService stuProductCatalogTemplateDataService;
    @Autowired
    private StuCommonClassifyCatalogMapper stuCommonClassifyCatalogMapper;

    /**
     * 查询产品（含章节层级）列表
     */
    @PreAuthorize("@ss.hasPermi('product:productCatalog:list')")
    @GetMapping("/list")
    public TableDataInfo list(StuProductCatalog stuProductCatalog) {
        startPage();
        List<StuProductCatalog> list = stuProductCatalogService.selectStuProductCatalogList(stuProductCatalog);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('product:productCatalog:list')")
    @GetMapping("/plist")
    public TableDataInfo productList(StuProductCatalog stuProductCatalog) {
        startPage();
        List<StuProductCatalog> list = stuProductCatalogService.selectProductCatalogList(stuProductCatalog);
        return getDataTable(list);
    }

    /**
     * 导出产品（含章节层级）列表
     */
    @PreAuthorize("@ss.hasPermi('product:productCatalog:export')")
    @Log(title = "产品（含章节层级）", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(StuProductCatalog stuProductCatalog) {
        List<StuProductCatalog> list = stuProductCatalogService.selectStuProductCatalogList(stuProductCatalog);
        ExcelUtil<StuProductCatalog> util = new ExcelUtil<StuProductCatalog>(StuProductCatalog.class);
        return util.exportExcel(list, "productCatalog");
    }

    /**
     * 获取产品（含章节层级）详细信息
     */
    @PreAuthorize("@ss.hasPermi('product:productCatalog:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(stuProductCatalogService.selectStuProductCatalogById(id));
    }

    /**
     * 新增产品（含章节层级）
     */
    @Transactional
    @PreAuthorize("@ss.hasPermi('product:productCatalog:add')")
    @Log(title = "产品（含章节层级）", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody StuProductCatalog stuProductCatalog) {
        stuProductCatalog = (StuProductCatalog) BeanUtils.initBeanPublicProperties(stuProductCatalog, "add");
        //catalogType=2 表示添加的是小节，默认创建对应模板数据
        if ("2".equals(stuProductCatalog.getCatalogType())) {

            List<StuCommonClassifyCatalog> stuCommonClassifyCatalogList = getStuCommonClassifyCatalogList(stuProductCatalog);

            if (stuCommonClassifyCatalogList.size() > 0) {
                stuCommonClassifyCatalogMapper.insertStuCommonClassifyCatalogList(stuCommonClassifyCatalogList);
            }
        }
        return toAjax(stuProductCatalogService.insertStuProductCatalog(stuProductCatalog));
    }

    /**
     * 根据模板ID获取模板数据
     *
     * @param stuProductCatalog
     * @return
     */
    List<StuCommonClassifyCatalog> stuCommonClassifyCatalogList = null;
    public List<StuCommonClassifyCatalog> getStuCommonClassifyCatalogList(StuProductCatalog stuProductCatalog) {
        StuProductCatalogTemplateData stuProductCatalogTemplateData = new StuProductCatalogTemplateData();
        stuProductCatalogTemplateData.setProductId(stuProductCatalog.getProductTemplateId());
        List<StuProductCatalogTemplateData> stuProductCatalogTemplateDataList = stuProductCatalogTemplateDataService.selectStuProductCatalogTemplateDataList(stuProductCatalogTemplateData);
        List<StuProductCatalogTemplateData> treeDataList = stuProductCatalogTemplateDataService.selectStuProductCatalogTemplateDataTree(stuProductCatalogTemplateDataList);
        stuCommonClassifyCatalogList = new ArrayList<>();
        builderStuCommonClassifyCatalogList(treeDataList,stuProductCatalog.getId());
        return stuCommonClassifyCatalogList;
    }



    public void builderStuCommonClassifyCatalogList(List<StuProductCatalogTemplateData> tdlist,String proudctId){

        for(StuProductCatalogTemplateData td: tdlist){

             if(td.getChildren()!=null && td.getChildren().size()>0){
                 setProp(td,td.getChildren(),proudctId);
                 builderStuCommonClassifyCatalogList(td.getChildren(),proudctId);
             }else {
                setProp(td,null,proudctId);
             }

         }

    }


    public void setProp(StuProductCatalogTemplateData td,List<StuProductCatalogTemplateData> children, String productId) {
        StuCommonClassifyCatalog ptd = setPro(td,productId,"0");
        StuCommonClassifyCatalog temptd = ptd;
        if(!dataIsExist(ptd)){
            stuCommonClassifyCatalogList.add(ptd);
        }else {
             ptd =  stuCommonClassifyCatalogList.stream().filter(t->temptd.getCode().equals(t.getCode())).findFirst().get();

        }
        if(children!=null && children.size()>0){
            for(StuProductCatalogTemplateData child:children){
                StuCommonClassifyCatalog ctd = setPro(child,productId,ptd.getId());
                if(!dataIsExist(ctd)){
                    stuCommonClassifyCatalogList.add(ctd);
                }

            }
        }

    }

    public boolean dataIsExist(StuCommonClassifyCatalog d){
        boolean flag = false;
        if(stuCommonClassifyCatalogList!=null && stuCommonClassifyCatalogList.size()>0){
            for(StuCommonClassifyCatalog c : stuCommonClassifyCatalogList){
                if(StringUtils.isNotEmpty(c.getCode()) && c.getCode().equals(d.getCode())){
                    flag = true;
                }
            }
        }

        return flag;
    }

    /**
     * 设置属性
     *
     * @param td
     * @param productId
     * @return
     */
    public StuCommonClassifyCatalog setPro(StuProductCatalogTemplateData td, String productId,String parentId) {
        StuCommonClassifyCatalog stuCommonClassifyCatalog = new StuCommonClassifyCatalog();
        stuCommonClassifyCatalog.setId(IdUtils.simpleUUID());
        stuCommonClassifyCatalog.setBelongProductId(productId);
        stuCommonClassifyCatalog.setProductCatalogTemplateId(td.getId());
        stuCommonClassifyCatalog.setCatalogCode(stuCommonClassifyCatalog.getId());
        stuCommonClassifyCatalog.setCode(td.getCatalogCode());
        stuCommonClassifyCatalog.setCatalogName(td.getCatalogName());
        stuCommonClassifyCatalog.setCatalogIcon(td.getCatalogIcon());
        stuCommonClassifyCatalog.setCatalogSort(td.getCatalogSort());
        stuCommonClassifyCatalog.setCatalogShowStatus(td.getCatalogShowStatus());
        stuCommonClassifyCatalog.setIfOnlyCatalog(td.getIfOnlyCatalog());
        stuCommonClassifyCatalog.setCatalogLevel(td.getCatalogLevel());
        stuCommonClassifyCatalog.setCatalogParentId(parentId);
        stuCommonClassifyCatalog.setCatalogDescription(td.getCatalogDescription());
        stuCommonClassifyCatalog.setIfDirectOwnCourse(td.getIfDirectOwnCourse());
        stuCommonClassifyCatalog.setStuProductItemType(td.getStuProductItemType());
        stuCommonClassifyCatalog.setStuProductItemTemplateId(td.getStuProductItemTemplateId());
        stuCommonClassifyCatalog.setComponetRepRankType(td.getComponetRepRankType());
        stuCommonClassifyCatalog.setLearnComponetScore(td.getLearnComponetScore());
        stuCommonClassifyCatalog.setWeight(td.getWeight());
        stuCommonClassifyCatalog.setCreateBy(SecurityUtils.getUsername());
        stuCommonClassifyCatalog.setCreateTime(new Date());

        return stuCommonClassifyCatalog;
    }

    /**
     * 修改产品（含章节层级）
     */
    @PreAuthorize("@ss.hasPermi('product:productCatalog:edit')")
    @Log(title = "产品（含章节层级）", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody StuProductCatalog stuProductCatalog) {
        stuProductCatalog = (StuProductCatalog) BeanUtils.initBeanPublicProperties(stuProductCatalog, "update");
        return toAjax(stuProductCatalogService.updateStuProductCatalog(stuProductCatalog));
    }

    /**
     * 删除产品（含章节层级）
     */
    @PreAuthorize("@ss.hasPermi('product:productCatalog:remove')")
    @Log(title = "产品（含章节层级）", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(stuProductCatalogService.deleteStuProductCatalogByIds(ids));
    }
}
